package org.linlinjava.litemall.wx.web;

import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallMechanismGoodsService;
import org.linlinjava.litemall.db.service.LitemallOrderVoucherService;
import org.linlinjava.litemall.db.service.LitemallVoucherCommentService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx/voucher")
public class WxsMyVoucherController {

	private LitemallOrderVoucherService litemallOrderVoucherService;

	private LitemallMechanismGoodsService mechanismGoodsService;

	private LitemallVoucherCommentService litemallVoucherCommentService;

	private PlatformTransactionManager txManager;

	public WxsMyVoucherController(
		LitemallOrderVoucherService litemallOrderVoucherService,
		LitemallMechanismGoodsService mechanismGoodsService,
		LitemallVoucherCommentService litemallVoucherCommentService,
		PlatformTransactionManager txManager) {
		this.litemallOrderVoucherService = litemallOrderVoucherService;
		this.mechanismGoodsService = mechanismGoodsService;
		this.litemallVoucherCommentService = litemallVoucherCommentService;
		this.txManager = txManager;
	}

	@GetMapping("/list")
	public Object list(@LoginUser Integer userId,
                       @RequestParam(value = "showType", defaultValue = "1") Integer showType,
					   @RequestParam(value = "name", defaultValue = "") String name,
					   @RequestParam(value = "page", defaultValue = "1") Integer page,
					   @RequestParam(value = "size", defaultValue = "6") Integer size){
		if(userId == null){
			return ResponseUtil.unlogin();
		}

		List<LitemallVoucherOrderVo> myVoucherList = litemallOrderVoucherService.selectTotalMchanismSimpleInfo(userId, showType, name);
        List<LitemallVoucherOrderVom> beforePagevoucherOrderVomList;
        List<LitemallVoucherOrderVom> afterPagevoucherOrderVomList = null;
        int count = 0;
		if(myVoucherList.size()>0){
            beforePagevoucherOrderVomList = getVoucherOrderVomList(myVoucherList);
            count = beforePagevoucherOrderVomList.size();
            afterPagevoucherOrderVomList = beforePagevoucherOrderVomList.subList(page>1?(page-1)*size:0, page*size>count?count:page*size);
        }
		int totalPages = (int) Math.ceil((double) count / size);

        if(afterPagevoucherOrderVomList == null){
            afterPagevoucherOrderVomList = new ArrayList<>();
        }

		Map<String, Object> result = new HashMap<>(16);
		result.put("voucherList", afterPagevoucherOrderVomList);
		result.put("totalPages", totalPages);
		result.put("showType", showType);
		return ResponseUtil.ok(result);
	}

	private List<LitemallVoucherOrderVom> getVoucherOrderVomList(List<LitemallVoucherOrderVo> myVoucherList){
		List<LitemallVoucherOrderVom> voucherOrderVomList = null;
		List<LitemallVoucherOrderVov> voucherOrderVovList ;

		List<Integer> mechanismIdList = new ArrayList<>();

		if(myVoucherList.size()>0){
			voucherOrderVomList = new ArrayList<>();
			for(int i=0;i<myVoucherList.size();i++){
				Integer mechanismId = myVoucherList.get(i).getMechanismId();
				String mechanismName = myVoucherList.get(i).getMechanismName();
				String qualifications;
				if(myVoucherList.get(i).getQualifications().length == 0 || myVoucherList.get(i).getQualifications().equals("")){
					qualifications = "";
				}else {
					qualifications = myVoucherList.get(i).getQualifications()[0];
				}
				LitemallVoucherOrderVom voucherOrderVom = new LitemallVoucherOrderVom();

				if(!mechanismIdList.contains(mechanismId)){
					mechanismIdList.add(mechanismId);

					voucherOrderVom.setMechanismId(mechanismId);
					voucherOrderVom.setMechanismName(mechanismName);
					voucherOrderVom.setQualifications(qualifications);

					voucherOrderVomList.add(voucherOrderVom);
				}
			}
		}

		if(myVoucherList.size()>0 && voucherOrderVomList.size()>0){
			for(int i=0;i<voucherOrderVomList.size();i++){
				voucherOrderVovList = new ArrayList<>();
				for(int j=0;j<myVoucherList.size();j++){
					Integer mechanismId_1 = voucherOrderVomList.get(i).getMechanismId();
					Integer mechanismId_2 = myVoucherList.get(j).getMechanismId();

					Integer id = myVoucherList.get(j).getId();
					Integer goodsId = myVoucherList.get(j).getGoodsId();
					String orderSn = myVoucherList.get(j).getOrderSn();
					Byte commentsStatus = myVoucherList.get(j).getCommentsStatus();
					String picUrl = myVoucherList.get(j).getPicUrl();
					String goodsName = myVoucherList.get(j).getGoodsName();
					String discountsTime = myVoucherList.get(j).getDiscountsTime();

					if(mechanismId_1.equals(mechanismId_2)){
						LitemallVoucherOrderVov voucherOrderVov = new LitemallVoucherOrderVov();
						voucherOrderVov.setId(id);
						voucherOrderVov.setMechanismId(mechanismId_2);
						voucherOrderVov.setGoodsId(goodsId);
						voucherOrderVov.setOrderSn(orderSn);
						voucherOrderVov.setCommentsStatus(commentsStatus);
						voucherOrderVov.setPicUrl(picUrl);
						voucherOrderVov.setGoodsName(goodsName);
						voucherOrderVov.setDiscountsTime(discountsTime);
						voucherOrderVovList.add(voucherOrderVov);
					}
				}
				voucherOrderVomList.get(i).setVoucherOrderVov(voucherOrderVovList);
			}
		}

		return voucherOrderVomList;
	}

	//	代金券详情
	@GetMapping("/detail")
	public Object detail(@RequestParam(value = "id") Integer id){
		LitemallMechanismGoodsVo goods = mechanismGoodsService.showDetail(id);
		Map<String, Object> data = new HashMap<>(16);
		data.put("goods", goods);
		return ResponseUtil.ok(data);
	}

	/**
	 * 发表评论
	 *
	 *
	 * @param userId 用户ID
	 * @param voucherComment 评论内容
	 * @return 发表评论操作结果
	 *   成功则
	 *  {
	 *      errno: 0,
	 *      errmsg: '成功',
	 *      data: xxx
	 *  }
	 *   失败则 { errno: XXX, errmsg: XXX }
	 */
	@PostMapping("post")
	public Object post(@LoginUser Integer userId, @RequestBody LitemallVoucherComment voucherComment) {
		if(userId == null){
			return ResponseUtil.unlogin();
		}
		if(voucherComment == null){
			return ResponseUtil.badArgument();
		}

		voucherComment.setAddTime(LocalDateTime.now());
		voucherComment.setUserId(userId);
		// 开启事务管理
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);
		try {
			LitemallVoucherOrder voucherOrder = litemallOrderVoucherService.findById(voucherComment.getOrderId());

			if (voucherOrder == null) {
				return ResponseUtil.fail(403, "订单不存在");
			}

			int count = litemallVoucherCommentService.countWithOrderId(voucherComment.getOrderId());

			if (count == 0) {
				//修改订单详情里面的订单状态，评价
				voucherOrder.setCommentsStatus(new Byte("1"));
			} else {
				//修改订单详情里面的订单状态。追评
				voucherOrder.setCommentsStatus(new Byte("2"));
			}

			litemallVoucherCommentService.save(voucherComment);
			litemallOrderVoucherService.update(voucherOrder);
			txManager.commit(status);
		} catch (Exception ex) {
			txManager.rollback(status);
			return ResponseUtil.fail(403, "评价失败");
		}
		return ResponseUtil.ok(voucherComment);
	}
}